package com.nolydake.swingnote.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import com.nolydake.swingnote.model.NoteForder;
import com.nolydake.swingnote.util.StringUtil;

public class NoteForderDao extends AbstractDao {

    /** 日志对象 */
    private static final Logger LOG = Logger.getLogger(NoteForderDao.class);

    private static final Map<String, Column> COLUMNS = new LinkedHashMap<String, Column>();

    static {
        COLUMNS.put("id", new Column("id", "text", true, "唯一标识"));
        COLUMNS.put("name", new Column("name", "text", "名称"));
        COLUMNS.put("pid", new Column("pid", "text", "上级ID"));
        COLUMNS.put("lastUpdateTime", new Column("lastUpdateTime", "integer", "最后修改时间"));
    }

    @Override
    protected String initData() {

        PreparedStatement countStmt = null;
        ResultSet countRs = null;
        try {

            // 如果有数据的话，不进行数据数据的初始化了
            countStmt = connection.prepareStatement("select count(*) as cnt from " + getTableName());
            countRs = countStmt.executeQuery();
            if (countRs.next()) {
                int count = countRs.getInt(1);

                if (count > 0) {
                    return null;
                }
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("目录信息没有初始化数据，开始进行初始化...");
            }

            insertNoteForder("我的文件夹", null);

        } catch (SQLException e) {
            LOG.error(e.getMessage(), e);
        } finally {

            if (countRs != null) {
                try {
                    countRs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (countStmt != null) {
                try {
                    countStmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        // NoteForder forderRoot = new NoteForder();
        // forderRoot.name = "";
        // forderRoot.id = notesPath;
        // forderTreeRootNode.setUserObject(forderRoot);

        return null;
    }

    @Override
    protected String getTableName() {
        return "noteforder";
    }

    @Override
    protected Map<String, Column> getColumns() {
        return COLUMNS;
    }

    public List<NoteForder> loadNoteForderTree() throws SQLException {

        List<NoteForder> result = new ArrayList<NoteForder>();

        PreparedStatement stmt = connection.prepareStatement("select * from " + getTableName());
        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {

            NoteForder noteForder = new NoteForder();
            noteForder.id = rs.getString("id");
            noteForder.name = rs.getString("name");
            noteForder.lastUpdateTime = new Date(rs.getDate("lastUpdateTime").getTime());
            result.add(noteForder);
        }

        return result;
    }

    public NoteForder createNoteForder(String pid) {

        PreparedStatement stmt = null;

        try {
            stmt = connection.prepareStatement("select t.name from " + getTableName() + " t where t.pid = ?");
            stmt.setString(1, pid);

            ResultSet rs = stmt.executeQuery();

            Set<String> allNames = new HashSet<String>();

            while (rs.next()) {
                allNames.add(rs.getString(1));
            }

            // 准备完成了，开始准备新目录
            int count = 0;
            String defaultName = "新建文件夹";
            String evalName = defaultName;
            while (true) {

                if (!allNames.contains(evalName)) {
                    break;
                }

                count++;
                evalName = defaultName + "(" + count + ")";
            }

            return insertNoteForder(evalName, pid);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        return null;
    }

    private NoteForder insertNoteForder(String name, String pid) {

        PreparedStatement stmt = null;
        try {

            stmt = connection.prepareStatement(
                    "insert into " + getTableName() + " (id,name,pid, lastUpdateTime) values(?,?,?,?)");

            String id = StringUtil.randomUUID();
            java.sql.Date date = new java.sql.Date(Calendar.getInstance().getTimeInMillis());
            stmt.setString(1, id);
            stmt.setString(2, name);
            stmt.setString(3, pid);
            stmt.setDate(4, date);
            stmt.executeUpdate();

            NoteForder forder = new NoteForder();
            forder.id = id;
            forder.name = name;
            forder.pid = pid;
            forder.lastUpdateTime = date;

            return forder;
        } catch (SQLException e) {
            LOG.error(e.getMessage(), e);
        } finally {

            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public void delete(String id) {

        PreparedStatement stmt = null;
        try {
            stmt = connection.prepareStatement("delete from " + getTableName() + " t where t.id = ?");
            stmt.setString(1, id);
            stmt.executeUpdate();

        } catch (SQLException e) {
            LOG.error(e.getMessage(), e);
        } finally {

            if (stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 检查数量
     * 
     * @param forder
     *            过滤条件
     * @return 根据条件下的数目
     */
    public int count(NoteForder forder) {

        PreparedStatement countStmt = null;
        ResultSet countRs = null;
        try {
            
            StringBuffer sql = new StringBuffer();
            sql.append("select count(*) as cnt from " + getTableName());
            sql.append(" t where ");
            
            sql.append(" ");
            

            // 如果有数据的话，不进行数据数据的初始化了
            countStmt = connection.prepareStatement();
            countRs = countStmt.executeQuery();
            if (countRs.next()) {
                int count = countRs.getInt(1);

                if (count > 0) {
                    return null;
                }
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("目录信息没有初始化数据，开始进行初始化...");
            }

            insertNoteForder("我的文件夹", null);

        } catch (SQLException e) {
            LOG.error(e.getMessage(), e);
        } finally {

            if (countRs != null) {
                try {
                    countRs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (countStmt != null) {
                try {
                    countStmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

        return 0;
    }
}
